package com.hunliji.monitor.share.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 解密方法
 * @author wuchen
 */
public class DecryptUtil {
    /**
     * 解密一次的的处理长度
     */
    private static Integer DECRYPT_ONE_HANDLE_LEN = 16;

    /**
     * 将key转为byte
     * @param key
     * @return
     */
    public static byte[] getKeyByte(String key){
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            // won't happen
        }
        byte[] keyByte = digest.digest(key.getBytes(StandardCharsets.UTF_8));
        return keyByte;
    }

    /**
     * 解密方法
     * @param base64
     * @return
     * @throws Exception
     */
    public static String decrypt(String base64,String key) throws Exception {
        byte[] decode = Base64.getDecoder().decode(base64);
        Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
        byte[] iv = new byte[DECRYPT_ONE_HANDLE_LEN];
        System.arraycopy(decode, 0, iv, 0, DECRYPT_ONE_HANDLE_LEN);
        byte[] data = new byte[decode.length - DECRYPT_ONE_HANDLE_LEN];
        System.arraycopy(decode, DECRYPT_ONE_HANDLE_LEN, data, 0, data.length);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(getKeyByte(key), "AES"), new IvParameterSpec(iv));
        byte[] r = cipher.doFinal(data);
        if (r.length > 0) {
            int p = r.length - 1;
            for (; p >= 0 && r[p] <= DECRYPT_ONE_HANDLE_LEN; p--) {
            }
            if (p != r.length - 1) {
                byte[] rr = new byte[p + 1];
                System.arraycopy(r, 0, rr, 0, p + 1);
                r = rr;
            }
        }
        return new String(r, StandardCharsets.UTF_8);
    }
}
